package com.kcsj.service;
//201902104020 李鑫元

import com.kcsj.dao.NoticeDao;
import com.kcsj.dao.OrderDao;
import com.kcsj.dao.WayBillDao;
import com.kcsj.domain.Order;
import com.kcsj.domain.WayBill;
import com.kcsj.domain.user.Notice;
import com.kcsj.domain.user.User;
import com.kcsj.service.user.UserService;
import com.kcsj.util.JdbcHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;

public class WayBillService {
    private static WayBillDao wayBillDao = WayBillDao.getInstance();
    private static WayBillService wayBillService = new WayBillService();

    public WayBillService() {
    }

    public static WayBillService getInstance() {
        return wayBillService;
    }

    public boolean add(WayBill wayBill) throws SQLException {
        Connection conn = JdbcHelper.getConn();
        boolean confirm = wayBillDao.add(wayBill, conn);
        conn.close();
        return confirm;
    }

    public boolean delete(String wayBillNo) throws SQLException {
        Connection conn = JdbcHelper.getConn();
        boolean confirm = wayBillDao.delete(wayBillNo, conn);
        conn.close();
        return confirm;
    }

    public boolean update(WayBill wayBill) throws SQLException {
        Connection conn = JdbcHelper.getConn();
        conn.setAutoCommit(false);
        boolean confirm = false;
        try {
            wayBillDao.update(wayBill, conn);
            int id = wayBill.getOrder().getCustomer().getId();
            User user = UserService.getInstance().find(id);
            Order order = wayBill.getOrder();
            order.setOrderStatus(wayBill.getWaybillStatus());
            OrderDao.getInstance().updateOrderStatus(order,conn);
            Notice notice = new Notice("客户","订单号："+
                    wayBill.getOrder().getOrderNo()+"已发货,运单号为"+wayBill.getWayBillNo(),"未读",user);
            NoticeDao.getInstance().add(notice,conn);
            confirm = true;
        }catch (SQLException e){
            conn.rollback();
        }finally {
            conn.commit();
            conn.setAutoCommit(true);
        }
        conn.close();
        return confirm;
    }

    public WayBill find(String orderNo) throws SQLException {
        Connection conn = JdbcHelper.getConn();
        WayBill wayBill = wayBillDao.find(orderNo, conn);
        conn.close();
        return wayBill;
    }

    public Collection<WayBill> findAll(Integer id) throws SQLException {
        Connection conn = JdbcHelper.getConn();
        Collection<WayBill> wayBill =wayBillDao.findAll(id,conn);
        conn.close();
        return wayBill;
    }
}



